var fs=require('fs')
var router=require('koa-router')()

function routerObj(url){
    let tmpPath=__dirname||url
    let routerFiles=fs.readdirSync(tmpPath).filter(item=>{
        return item.endsWith('.js')&&item!='index.js'
    })
    return routerFiles
}
function routerRegister(router,routerFiles){
    routerFiles.forEach(item=>{
        let a=require(__dirname+'/'+item)
        for(let x in a){
            let arr=x.split(' ')
            let rUrl=arr[1]
            let rMethod=arr[0]
            let rFunction=a[x]
            if(rMethod==='get'){
                router.get(rUrl,rFunction)
            }else if(rMethod==='post'){
                router.post(rUrl,rFunction)
            }else if(rMethod==='put'){
                router.put(rUrl,rFunction)
            }else if(rMethod==='delete'){
                router.delete(rUrl,rFunction)
            }
        }
    })
    return router.routes()
}

module.exports=function(){
    let routerFiles=routerObj()
    let fn=routerRegister(router,routerFiles)
    return fn
}